package cn.mazexal.examapi.utils;

import jakarta.servlet.ServletInputStream;
import jakarta.servlet.http.HttpServletRequest;

import java.util.Map;

/**
 * @author: Mazexal
 * Date: 2025/6/30
 */
public class RequestUtil {

    public static String httpServletRequestToString(HttpServletRequest request) throws Exception {

        ServletInputStream mServletInputStream = request.getInputStream();
        byte[] httpInData = new byte[request.getContentLength()];
        int retVal = -1;
        StringBuilder stringBuilder = new StringBuilder();

        while ((retVal = mServletInputStream.read(httpInData)) != -1) {
            for (int i = 0; i < retVal; i++) {
                stringBuilder.append(Character.toString((char) httpInData[i]));
            }
        }

        return stringBuilder.toString();
    }

    public static final String paramsMapToQueryString(Map<String, String[]> map) {
        if (map == null) {
            return "";
        }

        StringBuilder sbQuery = new StringBuilder();
        for (String key : map.keySet()) {
            for(String val : map.get(key)) {
                sbQuery.append(String.format("&%s=%s", key, val));
            }
        }
        if (sbQuery.length() > 0) {
            return sbQuery.substring(1);
        }

        return "";
    }
}
